package com.jobsika.server;

import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.core.CoreContainer;
import org.xml.sax.helpers.DefaultHandler;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.jobsika.client.rpc.UserService;
import com.jobsika.domain.RPCPost;
import com.jobsika.domain.RPCUser;
import com.jobsika.solr.crawler.Craigslist;
import com.jobsika.solr.crawler.DataUtil;
import com.jobsika.solr.domain.Post;
import com.jobsika.solr.domain.User;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class UserServiceImpl extends RemoteServiceServlet implements
		UserService {
	
	public UserServiceImpl() {
	}
	
	@Override
	public Integer initialize() {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser;
		try {
			check();
			parser = factory.newSAXParser();
			DefaultHandler sx = new Craigslist();
			String[] categories = {"acc", "ofc", "egr", "med", "sci", "bus", "csr", "edu", "fbh", "lab", "gov", "hum", "eng", "lgl", "mnu", "mar", "hea", "npo", "rej", "ret", "sls", "spa", "sec", "trd", "sad", "tch", "trp", "tfr", "web", "wri"};
			for (String category : categories) {
				try {
					Craigslist.parseURL(server, parser, sx, "http://sfbay.craigslist.org/sby/"+category+"/index.rss");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public RPCUser login(String requestUri) {
//		com.google.appengine.api.users.UserService userService = UserServiceFactory
//				.getUserService();
//		com.google.appengine.api.users.User user = userService.getCurrentUser();
		User user = new User("Bernard", "Wong", "bernardw@gmail.com", "UCB", "BOB");
		RPCUser rpc = new RPCUser();
//		if (user != null) {
//			String email = user.getEmail().toLowerCase();
//			User u = UserUtil.hasUser(pm, email);
//			if (u != null) {
//				rpc = DataUtil.toRPC(u);
//			} else {
//				rpc.setEmail(user.getEmail());
//				rpc.setFirstName(user.get);
//			}
//		rpc = DataUtil.toRPC(user);
		rpc.setLoggedIn(true);
		rpc.setRegistered(true);
//			rpc.setLogoutUrl(userService.createLogoutURL(requestUri));
//		} else {
//			rpc.setLoggedIn(false);
//			rpc.setLoginUrl(userService.createLoginURL(requestUri));
//		}
		return rpc;
	}

	@Override
	public RPCUser register(RPCUser user) {
//		User u = DataUtil.toRPC(user);
//		u.setRegistered(true);
//		UserUtil.persistUser(pm, u);
		user.setRegistered(true);
		return user;
	}

	@Override
	public RPCUser getUser(String email) {
//		return DataUtil.toRPC(UserUtil.getUser(pm, email));
		return null;
	}

	@Override
	public RPCPost getPost(String key) {
		try {
			check();
			SolrQuery solrQuery = new SolrQuery("id:"+key);
			QueryResponse response = server.query(solrQuery);
			List<Post> posts = response.getBeans(Post.class);
			RPCPost[] rpcs = toRPC(posts);
			if (rpcs.length > 0) {
				return rpcs[0];
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public RPCUser[] getUsers(int page, int limit) {
		long t0 = System.currentTimeMillis(); 
//		List<User> users = PMUtil.getUsers(pm, page, limit);
//		if (users.size() > 0) {
//			RPCUser[] results = new RPCUser[users.size()];
//			for (int i = 0; i < users.size(); i++) {
//				results[i] = DataUtil.toRPC(users.get(i));
//			}
//			return results;
//		}
		System.out.println(System.currentTimeMillis() - t0);
		return null;
	}

	@Override
	public RPCPost[] getPosts(int page, int limit) {
		try {
			check();
			SolrQuery solrQuery = new SolrQuery("id:[* TO *]");
			solrQuery.setRows(0);
			QueryResponse response = server.query(solrQuery);
			List<Post> posts = response.getBeans(Post.class);
			return toRPC(posts);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private CoreContainer coreContainer = null;
	private EmbeddedSolrServer server = null;
	
	public void check() throws Exception {
		if (coreContainer == null || server == null) {
			CoreContainer.Initializer initializer = new CoreContainer.Initializer();
			CoreContainer coreContainer = initializer.initialize();
			server = new EmbeddedSolrServer(coreContainer, "");
		}
	}

	public RPCPost[] search(int page, int limit, String query) {
		try {
			check();
			SolrQuery solrQuery = new SolrQuery("body:"+query);
			QueryResponse response = server.query(solrQuery);
			List<Post> posts = response.getBeans(Post.class);
			return toRPC(posts);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private RPCPost[] toRPC(List<Post> posts) {
		if (posts.size() > 0) {
			RPCPost[] results = new RPCPost[posts.size()];
			for (int i = 0; i < posts.size(); i++) {
				results[i] = DataUtil.toRPC(posts.get(i));
			}
			return results;
		}
		return null;
	}
}